/**
    Copyright (c) 2010 yakiimo02
    Distributed under the New BSD License.
    See included license.txt or http://www.yakiimo3d.com/NewBSDLicense.txt
**/

/**
    LICENSE

    Copyright (c) 2006-2008 Kevin Beason (kevin.beason@gmail.com)

    Permission is hereby granted, free of charge, to any person obtaining
    a copy of this software and associated documentation files (the
    "Software"), to deal in the Software without restriction, including
    without limitation the rights to use, copy, modify, merge, publish,
    distribute, sublicense, and/or sell copies of the Software, and to
    permit persons to whom the Software is furnished to do so, subject to
    the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include "DXUT.h"
#include "DXHelper.h"
#include "DataBufferDX11.h"
#include "optimized/SmallPtTask.h"
#include "optimized/SphereSOA.h"
#include "optimized/SmallPtCPU_MT.h"

namespace OPT
{

/**
*/
Vec TracePixelTask::Radiance( const Ray &r_ ) const
{
    int depth = 0;

    SPT_FLOAT_OPT distToIntersect;          // distance to intersection
    int id=-1;                              // id of intersected object
    Ray ray=r_;
    // L0 = Le0 + f0*(L1)
    //    = Le0 + f0*(Le1 + f1*L2)
    //    = Le0 + f0*(Le1 + f1*(Le2 + f2*(L3))
    //    = Le0 + f0*(Le1 + f1*(Le2 + f2*(Le3 + f3*(L4)))
    //    = ...
    //    = Le0 + f0*Le1 + f0*f1*Le2 + f0*f1*f2*Le3 + f0*f1*f2*f3*Le4 + ...
    Vec cl(0.0f,0.0f,0.0f);  // accumulated color
    Vec cf(1.0f,1.0f,1.0f);  // accumulated reflectance
    
    //while (1)
    for( ; ; )
    {
        // offset to avoid self-intersections
        //ray.o = ray.o + ray.d*0.0027f;
        //ray.o = ray.o + ray.d*0.002f;
        if ( !Intersect(ray, distToIntersect, id) ) {
            // if miss, return black
            return cl; 
        }

        const Sphere &obj = spheresOPT[id];        // the hit object
        cl = cl + cf.mult(obj.emission);
        
        Vec x=ray.o+ray.d*distToIntersect;
        //Vec n=(x-obj.position).norm();
        Vec n = VectorNormalize( (x-obj.position) );
        Vec nl=n.dot(ray.d)<0?n:n*-1.0f;
        Vec f=obj.color;
        //SPT_FLOAT_OPT p = f.x>f.y && f.x>f.z ? f.x : f.y>f.z ? f.y : f.z; // max refl

        //if (++depth>5) if (drand48()<p) f=f*(1/p); else return cl; //R.R.
        if (++depth>5) {
            // Same as SmallPtGPU remove Russian Roulette
            return cl; 
        }

        cf = cf.mult(f);
        // Ideal DIFFUSE reflection
        if (obj.refl == DIFF)
        {                  
            SPT_FLOAT_OPT r1=2.0f*M_PI*drand48();
            SPT_FLOAT_OPT r2=drand48();
            SPT_FLOAT_OPT r2s=sqrtf_opt(r2);
            
            Vec w = nl;
            //Vec u = ((fabs(w.x)>0.1f?Vec(0.0f,1.0f):Vec(1.0f))%w).norm();
            Vec u = VectorNormalize( ((fabs(w.x)>0.1f?Vec(0.0f,1.0f):Vec(1.0f))%w) );
            Vec v = w%u;
            //Vec d = (u*cosf(r1)*r2s + v*sinf(r1)*r2s + w*sqrtf_opt(1.0f-r2)).norm();
            Vec d = VectorNormalize( (u*cosf(r1)*r2s + v*sinf(r1)*r2s + w*sqrtf_opt(1.0f-r2)) );
            ray = Ray(x,d);
            continue;
        }
        // Ideal SPECULAR reflection
        else if (obj.refl == SPEC)
        {           
            ray = Ray(x,ray.d-n*2.0f*n.dot(ray.d));
            continue;
        }
        
        Ray reflRay(x, ray.d-n*2.0f*n.dot(ray.d));     // Ideal dielectric REFRACTION
        bool into = n.dot(nl)>0.0f;                    // Ray from outside going in?
        SPT_FLOAT_OPT nc=1.0f;
        SPT_FLOAT_OPT nt=1.5f;
        SPT_FLOAT_OPT nnt=into?nc/nt:nt/nc;
        SPT_FLOAT_OPT ddn=ray.d.dot(nl);
        SPT_FLOAT_OPT cos2t;
        
        // Total internal reflection
        if( (cos2t=1.0f-nnt*nnt*(1.0f-ddn*ddn))<0.0f )
        {    
            ray = reflRay;
            continue;
        }
        
        //Vec tdir = (ray.d*nnt - n*((into?1.0f:-1.0f)*(ddn*nnt+sqrtf_opt(cos2t)))).norm();
        Vec tdir = VectorNormalize( (ray.d*nnt - n*((into?1.0f:-1.0f)*(ddn*nnt+sqrtf_opt(cos2t)))) );
        
        const SPT_FLOAT_OPT a=nt-nc;
        const SPT_FLOAT_OPT b=nt+nc;
        const SPT_FLOAT_OPT R0=a*a/(b*b);
        const SPT_FLOAT_OPT c = 1-(into?-ddn:tdir.dot(n));
        
        const SPT_FLOAT_OPT Re=R0+(1-R0)*c*c*c*c*c;
        const SPT_FLOAT_OPT Tr=1-Re;
        const SPT_FLOAT_OPT P=.25f+.5f*Re;
        const SPT_FLOAT_OPT RP=Re/P,TP=Tr/(1.0f-P);
        
        // reflection
        if (drand48()<P)
        {      
            cf = cf*RP;
            ray = reflRay;
        } 
        // refraction
        else 
        {                 
            cf = cf*TP;
            ray = Ray( x, tdir );
        }
    }
}

/**
*/
bool TracePixelTask::DoRange( CWorkerThread* pThread, const CRange &Range ) const
{
    const int samps = 1;

    Vec* pBuffer = m_pSmallPT_MT->GetpBuffer();
    Ray cam = m_pSmallPT_MT->GetCam();
    Vec cx = m_pSmallPT_MT->GetCx();
    Vec cy = m_pSmallPT_MT->GetCy();
    const unsigned int nWidth = m_pSmallPT_MT->GetWidth();
    const unsigned int nHeight = m_pSmallPT_MT->GetHeight();

    for(int iEntity= Range.begin; iEntity < Range.end; iEntity++)
    {
        unsigned int i=iEntity;
        unsigned int x=iEntity%nWidth;
        unsigned int y=nHeight-1-iEntity/nWidth;

        Vec pixel = (pBuffer)[ i ];

        // 2x2 subpixel rows
        for(int sy=0; sy<2; sy++)     
        {
            // 2x2 subpixel cols
            for (int sx=0; sx<2; sx++)
            {        
                Vec r= Vec();
                for (int s=0; s<samps; s++)
                {
                    const SPT_FLOAT_OPT r1=2.0f*drand48();
                    const SPT_FLOAT_OPT dx=r1<1.0f ? sqrtf_opt(r1)-1.0f: 1.0f-sqrtf_opt(2.0f-r1); // [-1,1]
                    const SPT_FLOAT_OPT r2=2*drand48();
                    const SPT_FLOAT_OPT dy=r2<1.0f ? sqrtf_opt(r2)-1.0f: 1.0f-sqrtf_opt(2.0f-r2); // [-1,1]

                    Vec d = cx*( ( (sx+.5f + dx)/2.0f + x)/nWidth - .5f) +
                        cy*( ( (sy+.5f + dy)/2.0f + y)/nHeight - .5f) + cam.d;

                    //r = r + Radiance(Ray(cam.o+d*140.0f,d.norm()),0)*(1.0f/samps);
                    //r = r + Radiance(Ray(cam.o+d*140.0f,d.norm()));
                    r = r + Radiance(Ray(cam.o+d*140.0f, d=VectorNormalize(d)));
                } // Camera rays are pushed ^^^^^ forward to start in interior

                pixel = pixel + r * .25f;
            }
        }

        (pBuffer)[ i ] = pixel;
    }		
    return true;
}

/**
*/
bool RootTask::Run( CWorkerThread* pThread )
{
    bool bResult = true;

    CWorkerThread*		pWorkerThread;
    TracePixelTask      tracePixelTask;

    tracePixelTask.SetpSmallPtCPU_MT( m_pSmallPT_MT );

    pWorkerThread = CWorkerThread::GetCurrent();

    bResult = ParallelFor( pWorkerThread, &tracePixelTask, CRange(0, m_nPixelCnt, 500) );

    return bResult;
}

}